package cn.oms.oms.service.impl;

import cn.oms.oms.entity.Patient;
import cn.oms.oms.entity.User;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.PatientMapper;
import cn.oms.oms.mapper.UserMapper;
import cn.oms.oms.service.IUserService;
import cn.oms.oms.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public PatientMapper patientMapper;

    /**
     * 用户注册的方法
     * @param registerVo
     * @return
     */
    @Override
    public String registerUser(RegisterVo registerVo) {

        User user = userMapper.findUserByUsername(registerVo.getUsername());
        //4.如果用户存在抛出异常
        if(user!=null){
            throw new ServiceException("用户名已存在!!!");
        }

        User u = new User();

        u.setUserName(registerVo.getUsername());
        u.setUserNickName(registerVo.getNickname());
        u.setUserPassword(registerVo.getPassword());
        u.setCreateTime(new Date());
        u.setUserType(0);
        u.setDeleteFlag(0);
        int num = userMapper.insert(u);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }

        //新增患者信息
        Patient patient = new Patient();
        patient.setUserId(u.getUserId());
        patient.setPatientName(u.getUserNickName());
        patient.setCreateTime(new Date());
        patient.setDeleteFlag(0);

        num = patientMapper.insert(patient);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }

        return "ok";
    }

    /**
     * 用户登录的方法
     * @param loginVo
     * @return
     */
    @Override
    public LoginRes userLogin(LoginVo loginVo) {

        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("userName",loginVo.getUsername());
        query.eq("userPassword",loginVo.getPassword());
        User user = userMapper.selectOne(query);
        if (user==null){
            throw new ServiceException("用户名或密码错误！请重新输入");
        }

        LoginRes res = new LoginRes();

        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",user.getUserId());
        queryWrapper.eq("deleteFlag",0);
        Patient patient = patientMapper.selectOne(queryWrapper);
        if (patient!=null){
            res.setPatientId(patient.getPatientId());
        }

        if (user.getUserType()==5){
            res.setStatus(1);
            res.setUrl("/user/admin/index_admin.html");
            return res;
        }else if (user.getUserType()==4){
            res.setStatus(1);
            res.setUrl("/user/pharmacy/index_pharmacy.html");
            return res;
        }else if (user.getUserType()==3){
            res.setStatus(1);
            res.setUrl("/user/doctor/index_doctor.html");
            return res;
        }else if (user.getUserType()==2){
            res.setStatus(1);
            res.setUrl("/user/nurse/index_nurse.html");
            return res;
        }else if (user.getUserType()==1){
            res.setStatus(1);
            res.setUrl("/user/billing/index_billing.html");
            return res;
        }else if (user.getUserType()==0){
            res.setStatus(1);
            res.setUrl("/user/patient/index_patient.html");
            return res;
        }

        res.setStatus(0);
        return res;
    }

    /**
     * 根据查询条件查询用户列表
     * @param userVo
     * @return
     */
    @Override
    public PageInfo<User> selectUserList(UserVo userVo) {
        QueryWrapper<User> query = new QueryWrapper<>();

        // 用户名或昵称模糊查询
        if (StringUtil.isNotEmpty(userVo.getPatientName())){
            query.like("userName",userVo.getPatientName()).or().like("userNickName",userVo.getPatientName());
        }

        // 用户类型查询
        if (userVo.getUserType()!=null){
            query.eq("userType",userVo.getUserType());
        }

        // 未删除用户
        query.eq("deleteFlag",0);

        //分页
        PageHelper.startPage(userVo.getPageNum(),userVo.getPageSize());

        // 查询用户列表
        List<User> users = userMapper.selectList(query);

        // 时间格式化
        for (User user: users) {
            // 创建时间格式化
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getCreateTime());
            user.setReturnCreateTime(date);
        }

        return new PageInfo<>(users);
    }

    /**
     * 根据用户ID查询用户详情
     * @param userVo
     * @return
     */
    @Override
    public User selectUserDetail(UserVo userVo) {
        QueryWrapper<User> query = new QueryWrapper<>();
        if (userVo.getUserId()!=null){
            query.eq("userId",userVo.getUserId());
        }

        // 未删除用户
        query.eq("deleteFlag",0);
        User user = userMapper.selectOne(query);

        if (user.getUserType()==0){
            user.setUserTypeName("用户");
        }
        if (user.getUserType()==1){
            user.setUserTypeName("缴费员");
        }
        if (user.getUserType()==2){
            user.setUserTypeName("护士");
        }
        if (user.getUserType()==3){
            user.setUserTypeName("医生");
        }
        if (user.getUserType()==4){
            user.setUserTypeName("药师");
        }
        if (user.getUserType()==5){
            user.setUserTypeName("管理员");
        }
        return user;
    }

    /**
     * 新增用户
     * @param userReqVo
     * @return
     */
    @Override
    public String addUser(UserReqVo userReqVo) {

        User user = new User();
        user.setUserName(userReqVo.getUserName());
        user.setUserNickName(userReqVo.getUserNickName());
        user.setUserPassword(userReqVo.getUserPassword());
        user.setCreateTime(new Date());
        user.setDeleteFlag(0);
        if (userReqVo.getUserType()==0||userReqVo.getUserType()==1||userReqVo.getUserType()==2||userReqVo.getUserType()==3||userReqVo.getUserType()==4||userReqVo.getUserType()==5){
            user.setUserType(userReqVo.getUserType());
        }else {
            throw new ServiceException("用户类型异常");
        }
        int num = userMapper.insert(user);

        if (num!=1){
            throw new ServiceException("数据库异常");
        }

        //新增患者信息
        Patient patient = new Patient();
        patient.setUserId(user.getUserId());
        patient.setCreateTime(new Date());
        patient.setDeleteFlag(0);

        num = patientMapper.insert(patient);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }

        return "ok";
    }

    /**
     * 修改用户
     * @param userReqVo
     * @return
     */
    @Override
    public String updateUser(UserReqVo userReqVo) {
        if (userReqVo.getUserId()==null){
            throw new ServiceException("参数异常，用户ID不能为空");
        }
        // 查询用户
        User user = userMapper.selectById(userReqVo);
        //拷贝
        BeanUtils.copyProperties(userReqVo,user);

        // 执行修改
        int num = userMapper.updateById(user);

        if (num!=1){
            throw new ServiceException("数据库异常");
        }
        return "ok";
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public String deleteUser(Integer id) {
        QueryWrapper<User> query = new QueryWrapper<>();

        if (id==null){
            throw new ServiceException("删除异常，患者不存在");
        }
        query.eq("userId",id);
        // 未删除用户
        query.eq("deleteFlag",0);
        User user = userMapper.selectOne(query);
        if (user==null){
            throw new ServiceException("患者不存在");
        }
        user.setDeleteFlag(1);
        int num = userMapper.updateById(user);

        if (num!=1){
            throw new ServiceException("数据库删除异常");
        }
        return "ok";
    }
}
